package com.echat.serviceapigateway.security.common;

import com.echat.serviceapigateway.security.model.authentication.Token;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.LocalDateTime;

/**
 * Created by chenmohan on 2018/08/30
 *
 * @description 统一接口返回对象
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class HttpResult<T> {

    protected static final String SUCCESS_DEFAULT_MSG = "ok";

    protected static final Integer SUCCESS_CODE = 0;

    /** 状态码,0表示接口请求成功 */
    private Integer code;

    /** 接口请求结果的文字说明 */
    private String msg;

    /** 接口返回的数据 */
    private T data;

    public static <T> HttpResult success(String msg, T data) {
        return new HttpResult<T>(SUCCESS_CODE, msg, data);
    }

    public static <T> HttpResult success(T data) {
        return new HttpResult<T>(SUCCESS_CODE, SUCCESS_DEFAULT_MSG, data);
    }

    public static <Void> HttpResult successWithMsg(String msg) {
        return new HttpResult<Void>(SUCCESS_CODE, msg, null);
    }

    public static <Void> HttpResult success() {
        return new HttpResult<Void>(SUCCESS_CODE, SUCCESS_DEFAULT_MSG, null);
    }

    public static <T> HttpResult failed(Integer code, String msg) {
        return new HttpResult<Void>(code, msg, null);
    }

    public static <T> HttpResult error(Integer code, String msg) {
        return new HttpResult<Void>(code, msg, null);
    }

    public static <T> HttpResult<T> token(Token t) {
        return new TokenResult(t.getAccessToken(), t.getAccessTokenExpire());
    }

    /**
     * 定制了 获取AccessToken接口的返回格式 {@link com.echat.serviceapigateway.security.controller.AuthenticateController}
     */
    @Getter
    @Setter
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @AllArgsConstructor
    static class TokenResult extends HttpResult {
        private String accessToken;

        @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm")
        private LocalDateTime accessTokenExpire;

    }

}
